<template>
    <div class="Index_view">
        <banner></banner>
        <list :list="list" ref="list"></list>
        <div class="loading">{{msg}}</div>
    </div>
</template>
<script>
import banner from "../components/banner";
import $ajax from "../plugins/ajax";
export default {
    components: {
        banner
    },
    beforeRouteEnter: async function(to, from, next) {
        var res = await $ajax("/goodList?page=1");
        next(vm => {
            // 如果已经存在内容 则不添加
            if (vm.list.length == 0) {
                vm.list.push(...res.data);
                // 获取DOM更新之后的list元素
                vm.$nextTick(() => {
                    var el = vm.$refs.list.$el;
                    vm.h = parseFloat(getComputedStyle(el, null).height);
                    vm.ot = el.offsetTop;
                });
            }
        });
    },
    data() {
        return {
            list: [],
            page: 1,
            flag: true,
            msg: "正在加载中...",
            h: 0,
            ot: 0
        };
    },
    created() {
        this.bindScroll();
    },
    methods: {
        bindScroll() {
            window.addEventListener("scroll",this.scrollHandle.bind(this));
        },
        scrollHandle() {
            if (this.flag) {
                var H = window.innerHeight;
                // console.log(H)
                var st =
                    document.body.scrollTop ||
                    document.documentElement.scrollTop;
                if (this.h + this.ot <= H + st) {
                    this.flag = false;
                    this.getList();
                }
            }
        },
        getList: async function() {
            // this.$store.commit("loading", true);
            this.page++;
            var res = await this.$ajax("/goodList?page=" + this.page);
            if(res.data.length){
                this.list.push(...res.data);
                this.$nextTick(() => {
                    var el = this.$refs.list.$el;
                    this.h = parseFloat(getComputedStyle(el, null).height);
                    this.ot = el.offsetTop;
                });
                this.flag = true;
            }else{
                window.removeEventListener("scroll",this.scrollHandle.bind(this));
                this.msg="我是有底线的"
            }
            // this.$store.commit("loading", false);
        }
    }
};
</script>

<style scoped>
.loading {
    width: 1200px;
    text-align: center;
    margin: 0 auto;
    line-height: 50px;
    background: white;
    color: purple;
    border-radius: 5px;
}
</style>